import React, { createContext, useState, useContext, useEffect } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage';

export const AuthContext = createContext();
export const useAuth = () => useContext(AuthContext)
export const baseURL = 'http://192.168.253.1:8080'


const AuthProvider = ({ children }) => {
    // const [user, setUser] = useState({})
    let myuser = ''
    useEffect(() => {
        AsyncStorage.getItem('user', function(err){
            console.log(err);
            console.log(222);
        }).then(res=>{
            setUser(res.data[0])
        })
    }, [])
    const delUser = () => {
        AsyncStorage.removeItem('user', function (error) {
            if (error) {
                alert('退出登录失败，请重试')
            } else {
                async function fetchData() {
                    try {
                        AsyncStorage.removeItem('mycropsid', function (error) {
                            if (error) {
                                alert('退出登录失败，请重试')
                            } 
                        })
                        AsyncStorage.removeItem('user', function (error) {
                            if (error) {
                                alert('退出登录失败，请重试')
                            } else {
                                async function fetchData() {
                                    try {
                                        const users = await AsyncStorage.getItem('user')
                                        // console.log(users);
                                        if (users !== null) {
                                        }
                                        setUser(JSON.parse(users))
                                        alert("退出登录成功")
                                    } catch (e) {
                                        return e
                                    }
                
                                }
                                fetchData()
                                alert('退出登录')
                            }
                        })
                    } catch (e) {
                        return e
                    }

                }
                fetchData()
                alert('退出登录')
            }
        })
    }
    const [user, setUser] = useState()
    return (
        <AuthContext.Provider value={{ user, setUser, delUser }}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthProvider